package com.golden.thumbnail.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.golden.thumbnail.callable.CompressCallable;
import com.golden.thumbnail.vo.TaskVO;

public class WorkerThread implements Runnable {
	
	private Queue<TaskVO> queue = null;
	
	private int defaultThreadCount = 30;
	
	private AtomicInteger currentTaskCount = new AtomicInteger(0);
	
	private ExecutorService executorService = null;
	
	private Thread testThread = null;
	
	public WorkerThread() {
		queue = new LinkedTransferQueue<TaskVO>();
		executorService = Executors.newCachedThreadPool();
		testThread = new Thread(new CpuTestThread());
	}
	
	public WorkerThread(int threadCount) {
		this.defaultThreadCount = threadCount;
		executorService = Executors.newCachedThreadPool();
		testThread = new Thread(new CpuTestThread());
	}
	
	public void addTask(TaskVO taskVO) {
		queue.add(taskVO);
	}

	public void run() {
		List<Callable<TaskVO>> list = new ArrayList<Callable<TaskVO>>();
		while(!Thread.interrupted()) {
			if(queue.size() > 0) {
				if(currentTaskCount.intValue() < defaultThreadCount) {
					list.add(queue.poll().getCallabel());
					currentTaskCount.getAndIncrement();
				}
				try {
					System.out.println(list.size());
					
					executorService.invokeAll(list).stream().map(future->{
						try {
							TaskVO taskVO = future.get();
							list.remove(taskVO.getCallabel());
							if(!taskVO.getIsSuccess())
								queue.add(taskVO);
							return taskVO;
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}).forEach(System.out::println);
					currentTaskCount.getAndDecrement();
					
				} catch (InterruptedException e) {
					e.printStackTrace();
					testThread.interrupt();
				}
			}
			Random random = new Random();
			try {
				Thread.sleep(random.nextInt(1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
				testThread.interrupt();
			}
		}
	}
	
	class CpuTestThread implements Runnable {

		public void run() {
			while(!Thread.interrupted()) {
				int count = 5;
				int temp = 0;
				do {
					double combined = getCupInfo();
					if(combined > 0.90) {
						temp = 1;
					} else if(combined > 0.80) {
						temp = 5;
					} else if(combined > 0.50)  {
						temp = 10;
					} else if(combined > 0.30)  {
						temp = 30;
					} 
					count--;
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} while(count > 1);
				defaultThreadCount = temp;
			}
		}
	}
	
	public static double getCupInfo() {
		Sigar sigar = new Sigar();  
		CpuPerc cpuList[] = null;   
		double combined = 0.0;
        try {   
            cpuList = sigar.getCpuPercList();   
        } catch (SigarException e) {   
            e.printStackTrace();   
            return 0;   
        }   
        for (int i = 0; i < cpuList.length; i++) {   
        	combined += cpuList[i].getCombined();
        	System.out.println("cpu " + i + " " + CpuPerc.format(cpuList[i].getCombined()));
        }   
        
        return combined / cpuList.length;
	}
	
	
	
}